<script setup>

import {ref, onMounted, watch, computed} from 'vue';
import axios from "axios";
import { message } from 'ant-design-vue';
import moment from "moment"

// 查询
const pageSize = ref(15);
const pageNo = ref(1)
const items = ref([]);
const loading = ref(true);
const confirmLoading = ref(false);
const totalItems = ref(0);
const pagination = computed(() => ({
    total: totalItems.value,
    current: pageNo.value,
    pageSize: pageSize.value
})) 
const queryParams = ref({
    goodsNumber: "",
    goodsName: "",
    commonName: "",
    startTime: "",
    endTime: "",
    supplierName: ""
});
const columns = ref([
    {
        title: "商品编码",
        dataIndex: "goodsNumber",
        key: 'goodsNumber',
        resizable: true
    },
    {
        title: "商品名",
        dataIndex: "goodsName",
        key: 'goodsName',
        resizable: true
    },
    {
        title: "通用名称",
        dataIndex: "commonName",
        key: 'commonName',
        resizable: true
    },
    {
        title: "供应商名称",
        dataIndex: "supplierName",
        key: 'supplierName',
        resizable: true
    },
    {
        title: "返点率(%)",
        dataIndex: "pointRate",
        key: 'pointRate',
        align: "center"
    },
    {
        title: "单价(元)",
        dataIndex: "unitPrice",
        key: 'unitPrice',
        align: "center"
    },
    {
        title: "税率(%)",
        dataIndex: "taxRate",
        key: 'taxRate',
        align: "center"
    },
    {
        title: "含税单价(元)",
        dataIndex: "taxUnitPrice",
        key: 'taxUnitPrice',
        align: "center"
    },
    {
        title: "零售价(元)",
        dataIndex: "retailPrice",
        key: 'retailPrice',
        align: "center"
    },
    {
        title: "新增时间",
        dataIndex: "createTime",
        key: 'createTime',
        resizable: true
    },
    {
        title: "修改时间",
        dataIndex: "updateTime",
        key: 'updateTime',
        resizable: true
    },
    {
        title: "操作人员",
        dataIndex: "username",
        key: 'username',
        align: "center"
    },
    {
        title: "操作",
        dataIndex: "action"
    }
])
const columnsAdd = ref([
    {
        title: "商品编码",
        dataIndex: "goodsNumber",
        key: 'goodsNumber'
    },
    {
        title: "商品名",
        dataIndex: "goodsName",
        key: 'goodsName'
    },
    {
        title: "通用名称",
        dataIndex: "commonName",
        key: 'commonName'
    },
    {
        title: "供应商名称",
        dataIndex: "supplierName",
        key: 'supplierName'
    },
    {
        title: "返点率(%)",
        dataIndex: "pointRate",
        key: 'pointRate',
        align: "center"
    },
    {
        title: "单价(元)",
        dataIndex: "unitPrice",
        key: 'unitPrice',
        align: "center"
    },
    {
        title: "税率(%)",
        dataIndex: "taxRate",
        key: 'taxRate',
        align: "center"
    },
    {
        title: "含税单价(元)",
        dataIndex: "taxUnitPrice",
        key: 'taxUnitPrice',
        align: "center"
    },
    {
        title: "零售价(元)",
        dataIndex: "retailPrice",
        key: 'retailPrice',
        align: "center"
    },
    {
        title: "操作",
        dataIndex: "action",
        width: '70px'
    }
])
const open = ref(false);
const title = ref("");
const formData = ref({});

function loadItems({page, itemsPerPage}) {
    loading.value = true;
    pageNo.value = page
    pageSize.value = itemsPerPage
    axios.post('/MedicinePoint/getMedicinePointList', {
        page: page,
        pageSize: itemsPerPage,
        goodsNumber: queryParams.value.goodsNumber,
        goodsName: queryParams.value.goodsName,
        commonName: queryParams.value.commonName,
        supplierName: queryParams.value.supplierName,
        startTime: queryParams.value.startTime ? moment(queryParams.value.startTime.$d).format("YYYY-MM-DD HH:mm:ss") : '',
        endTime: queryParams.value.endTime ? moment(queryParams.value.endTime.$d).format("YYYY-MM-DD HH:mm:ss"): ""
    }).then(({data}) => {
        items.value = data.data.records;
        totalItems.value = data.data.total;
        loading.value = false;
    })
}

const medicineList = ref([]);
onMounted(() => {
    loadItems({page: 1, itemsPerPage: pageSize.value});
    axios.post('/Medicine/getMedicineList', {
        page: 1,
        pageSize: 10000,
        goodsNumber: "",
        goodsName: "",
        commonName: "",
        startTime: "",
        endTime: ""
    }).then(({data}) => {
        medicineList.value = data.data.records
    })
});

const dialogEnum = {
    update: "编辑",
    create: "新增"
}

function openData(data) {
    open.value = true
    title.value = dialogEnum.update
    formData.value = JSON.parse(JSON.stringify(data))
}

function submit() {
    if(title.value == dialogEnum.create) {
        confirmLoading.value = true
        axios.post("/User/addUser", formData.value).then(res => {
            if(res.data.code == 0) {
                message.success('新增成功！')
                confirmLoading.value = false;
                open.value = false;
                loadItems({page: 1, itemsPerPage: pageSize.value});
            } else {
                confirmLoading.value = false;
                message.error(res.data.message)
            }
        }, err => {
            confirmLoading.value = false;
            message.error(err.data.message)
        })
    } else if(title.value == dialogEnum.update) {
        confirmLoading.value = true
        axios.post("/MedicinePoint/updateMedicinePoint", formData.value).then(res => {
            if(res.data.code == 0) {
                message.success('修改成功！')
                confirmLoading.value = false;
                open.value = false;
                loadItems({page: 1, itemsPerPage: pageSize.value});
            } else {
                confirmLoading.value = false;
                message.error(res.data.message)
            }
        }, err => {
            confirmLoading.value = false;
            message.error(err.data.message)
        })
    }
}

function handleTabChange(pag){
    loadItems({page: pag.current, itemsPerPage: pag.pageSize})
}

function exportTemplate() {
    let a = document.createElement("a");
    // 必须放在/static 文件目录下  使用相对路径即可
    a.href = './pointBaseInfo.xlsx';
    a.download = '药品返点基础资料导入模板红色字段必填 .xlsx';
    a.style.display = 'none';
    document.body.appendChild(a);
    a.click();
    a.remove();
}

function exportList() {
    axios({
        method: "post",
        url: "/MedicinePoint/exportMedicinePointList",
        data: {
            page: pageNo.value,
            pageSize: pageSize.value,
            goodsNumber: queryParams.value.goodsNumber,
            goodsName: queryParams.value.goodsName,
            commonName: queryParams.value.commonName,
            supplierName: queryParams.value.supplierName,
            startTime: queryParams.value.startTime ? moment(queryParams.value.startTime.$d).format("YYYY-MM-DD HH:mm:ss") : '',
            endTime: queryParams.value.endTime ? moment(queryParams.value.endTime.$d).format("YYYY-MM-DD HH:mm:ss"): ""
        },
        responseType: 'blob'
    }).then(({data}) => {}, err => {
        let blob = new Blob([err.data], {type: "application/vnd.ms-excel"});
        let fileName = `药品基础资料.xlsx`
        if ("download" in document.createElement("a")) {
            // 支持a标签download的浏览器
            const link = document.createElement("a"); // 创建a标签
            link.download = fileName; // a标签添加属性
            link.style.display = "none";
            link.href = URL.createObjectURL(blob);
            document.body.appendChild(link);
            link.click(); // 执行下载
            URL.revokeObjectURL(link.href); // 释放url
            document.body.removeChild(link); // 释放标签
        } else {
            // 其他浏览器
            navigator.msSaveBlob(blob, fileName);
        }
    })
}

const fileList = ref([]);
function uploadFile(file) {
    var formData = new FormData();
    formData.append("file", file.file)
    axios({
        method: "post",
        url: "/MedicinePoint/importMedicinePoint",
        data: formData,
        headers: {
            'Content-Type': "multipart/form-data"
        }
    }).then(res => {
        message.success(res.data.message)
        loadItems({page: 1, itemsPerPage: pageSize.value});
    }, err => {
        message.error(err.data.message)
    })
}

const selectedRowKeys = ref([])
function onSelectChange(keys ) {
    selectedRowKeys.value = keys
}

function deleteList() {
    if(!selectedRowKeys.value.length) {
        message.error("请选择数据！")
        return
    }
    let obj = {
        medicinePointIdList: Object.values(selectedRowKeys.value)
    }
    axios.post('/MedicinePoint/disableMedicinePointBatch', obj).then(res => {
        if(res.data.code == 0) {
            message.success('删除成功！')
            loadItems({page: 1, itemsPerPage: pageSize.value});
        } else {
            message.error(res.data.message)
        }
    }, err => {
        message.error(err.data.message)
    })
}

const addShow = ref(false);
const addList = ref([]);
const addListId = ref(null);
const confirmLoadingAdd = ref(false);
function getAddShow() {
    addShow.value = true
    addList.value = []
    addListId.value = null
}

function addListPost() {
    let obj = {
        medicinePointList: addList.value
    }
    confirmLoadingAdd.value = true
    axios.post("/MedicinePoint/addMedicinePointBatch", obj).then(res => {
        setTimeout(() => {
            confirmLoadingAdd.value = false
        }, 3000)
        if(res.data.code == 0) {
            message.success('添加成功！')
            loadItems({page: 1, itemsPerPage: pageSize.value});
            confirmLoadingAdd.value = false
            addShow.value = false
        } else {
            message.error(res.data.message)
            confirmLoadingAdd.value = false
        }
    }, err => {
        message.error(err.data.message)
        confirmLoadingAdd.value = false
    })
}

function addListPush() {
    if(!addListId.value) {
        message.error("请选择添加行！")
        return
    }
    medicineList.value.forEach(item => {
        if(item.medicineId == addListId.value) {
            let obj = JSON.parse(JSON.stringify(item))
            addList.value.push(obj)
            // let sum = 0
            // addList.value.forEach(k => {
            //     if(k.medicineId == item.medicineId) {
            //         message.error("该商品已重复！")
            //         sum ++
            //     }
            // })
            // if(!sum) {
            //     addList.value.push(item)
            // }
        }
    })
}

function handleResizeColumn(w, col) {
  col.width = w;
}

const filterOption = (input, option) => {
  return option.goodsName.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};
</script>

<template>
    <a-spin size="large" :spinning="loading">
        <a-card title="药品返点基础资料管理">
            <a-row>
                <a-form
                layout="inline"
                :model="queryParams"
                :colon="false">
                    <a-form-item label="商品编码" style="margin-bottom: 25px;">
                        <a-input v-model:value="queryParams.goodsNumber" placeholder="商品编码" allow-clear @keyup.enter="loadItems({page: 1, itemsPerPage: pageSize})"></a-input>
                    </a-form-item>
                    <a-form-item label="商品名">
                        <a-input v-model:value="queryParams.goodsName" placeholder="商品名" allow-clear @keyup.enter="loadItems({page: 1, itemsPerPage: pageSize})"></a-input>
                    </a-form-item>
                    <a-form-item label="通用名称">
                        <a-input v-model:value="queryParams.commonName" placeholder="通用名称" allow-clear @keyup.enter="loadItems({page: 1, itemsPerPage: pageSize})"></a-input>
                    </a-form-item>
                    <a-form-item label="供应商名称">
                        <a-input v-model:value="queryParams.supplierName" placeholder="供应商名称" allow-clear @keyup.enter="loadItems({page: 1, itemsPerPage: pageSize})"></a-input>
                    </a-form-item>
                    <a-form-item label="开始时间">
                        <a-date-picker show-time v-model:value="queryParams.startTime" placeholder="开始时间"></a-date-picker>
                    </a-form-item>
                    <a-form-item label="结束时间">
                        <a-date-picker show-time v-model:value="queryParams.endTime" placeholder="结束时间"></a-date-picker>
                    </a-form-item>
                </a-form>
            </a-row>
            <a-row style="margin-bottom: 25px;">
                <a-button @click="loadItems({page: 1, itemsPerPage: pageSize})">查询</a-button>&nbsp;
                    <a-button @click="getAddShow">添加</a-button>&nbsp;
                    <a-popconfirm title="确认删除该数据？" @confirm="deleteList">
                            <a-button danger>删除</a-button>
                        </a-popconfirm>&nbsp;
                    <a-button @click="exportList">导出</a-button>&nbsp;
                    <a-button @click="exportTemplate">下载模板</a-button>&nbsp;
                    <a-upload :file-list="fileList" :customRequest="uploadFile">
                        <a-button>导入</a-button>
                    </a-upload>
            </a-row>
            <a-table
            @resizeColumn="handleResizeColumn"
            :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
            rowKey="medicinePointId"
            :dataSource="items"
            :columns="columns"
            :pagination="pagination"
            @change="handleTabChange">
                <template #bodyCell="{ column, text, record }">
                    <template v-if="column.dataIndex == 'pointRate'">
                        <span>{{ record.pointRate.toFixed(2) }}%</span>
                    </template>
                    <template v-if="column.dataIndex == 'taxRate'">
                        <span>{{ record.taxRate.toFixed(2) }}%</span>
                    </template>
                    <tempalte v-if="column.dataIndex == 'status'">
                        <span v-if="record.status">使用中</span>
                        <span v-if="!record.status">未使用</span>
                    </tempalte>
                    <tempalte v-if="column.dataIndex == 'action'">
                        <a @click="openData(record)">修改</a>
                    </tempalte>
                </template>
            </a-table>            
        </a-card>

        <a-modal
        v-model:open="addShow"
        title="基础资料"
        cancelText="关闭"
        okText="确定"
        width="66%"
        :confirmLoading="confirmLoadingAdd"
        @ok="addListPost">
            <a-table
            :dataSource="addList"
            :columns="columnsAdd"
            :pagination="false">
                <template #bodyCell="{column, text, record, index}">
                    <template v-if="column.dataIndex == 'goodsNumber'">
                        <a-input v-model:value="record.goodsNumber"></a-input>
                    </template>
                    <template v-if="column.dataIndex == 'goodsName'">
                        <a-input v-model:value="record.goodsName"></a-input>
                    </template>
                    <template v-if="column.dataIndex == 'commonName'">
                        <a-input v-model:value="record.commonName"></a-input>
                    </template>
                    <template v-if="column.dataIndex == 'supplierName'">
                        <a-input v-model:value="record.supplierName"></a-input>
                    </template>
                    <template v-if="column.dataIndex == 'pointRate'">
                        <a-input v-model:value="record.pointRate"></a-input>
                    </template>
                    <template v-if="column.dataIndex == 'unitPrice'">
                        <a-input v-model:value="record.unitPrice"></a-input>
                    </template>
                    <template v-if="column.dataIndex == 'taxRate'">
                        <a-input v-model:value="record.taxRate"></a-input>
                    </template>
                    <template v-if="column.dataIndex == 'taxUnitPrice'">
                        <a-input v-model:value="record.taxUnitPrice"></a-input>
                    </template>
                    <template v-if="column.dataIndex == 'retailPrice'">
                        <a-input v-model:value="record.retailPrice"></a-input>
                    </template>
                    <template v-if="column.dataIndex == 'action'">
                        <a style="color: red;" @click="addList.splice(index, 1)">删除</a>
                    </template>
                </template>
            </a-table>
            <a-select
            v-model:value="addListId"
            placeholder="请选择添加的药品"
            show-search
            :filter-option="filterOption"
            :options="medicineList"
            :fieldNames="{
                label: 'goodsName',
                value: 'medicineId'
            }"
            style="width: 200px;">
            </a-select>
            <a-button @click="addListPush()">添加行</a-button>
            <template #footer>
                <a-button type=primary style="color:#fff;" @click="addListPost" :loading="confirmLoadingAdd">确定</a-button>
            </template>
        </a-modal>

        <a-modal
        v-model:open="open"
        :title="title"
        cancelText="关闭"
        okText="确定"
        :confirmLoading="confirmLoading"
        @ok="submit">
            <a-form
            :model="formData"
            :colon="false"
            :label-col="{ span: 5 }">
                <a-form-item
                label="商品编码"
                :rules="[{ required: true, message: '请输入商品编码！' }]">
                    <a-input
                    readonly
                    v-model:value="formData.goodsNumber"
                    placeholder="请输入商品编码"></a-input>
                </a-form-item>
                <a-form-item
                label="商品名"
                :rules="[{ required: true, message: '请输入商品名！' }]">
                    <a-input
                    readonly
                    v-model:value="formData.goodsName"
                    placeholder="请输入商品名"></a-input>
                </a-form-item>
                <a-form-item
                label="通用名称"
                :rules="[{ required: true, message: '请输入通用名称！' }]">
                    <a-input
                    readonly
                    v-model:value="formData.commonName"
                    placeholder="请输入通用名称"></a-input>
                </a-form-item>
                <a-form-item
                label="供应商名称"
                :rules="[{ required: true, message: '请输入供应商名称！' }]">
                    <a-input
                    readonly
                    v-model:value="formData.supplierName"
                    placeholder="请输入供应商名称"></a-input>
                </a-form-item>
                <a-form-item
                label="返点率"
                :rules="[{ required: true, message: '请输入返点率！' }]">
                    <a-input
                    v-model:value="formData.pointRate"
                    placeholder="请输入返点率"></a-input>
                </a-form-item>
                <a-form-item
                label="单价"
                :rules="[{ required: true, message: '请输入单价！' }]">
                    <a-input
                    v-model:value="formData.unitPrice"
                    placeholder="请输入单价"></a-input>
                </a-form-item>
                <a-form-item
                label="税率"
                :rules="[{ required: true, message: '请输入税率！' }]">
                    <a-input
                    v-model:value="formData.taxRate"
                    placeholder="请输入税率"></a-input>
                </a-form-item>
                <a-form-item
                label="含税单价"
                :rules="[{ required: true, message: '请输入含税单价！' }]">
                    <a-input
                    v-model:value="formData.taxUnitPrice"
                    placeholder="请输入含税单价"></a-input>
                </a-form-item>
                <a-form-item
                label="零售价"
                :rules="[{ required: true, message: '请输入零售价！' }]">
                    <a-input
                    v-model:value="formData.retailPrice"
                    placeholder="请输入零售价"></a-input>
                </a-form-item>
            </a-form>
            <template #footer>
                <a-button type=primary style="color:#fff;" @click="submit" :loading="confirmLoading">确定</a-button>
            </template>
        </a-modal>
    </a-spin>
</template>

<style scoped>
:deep(:where(.css-dev-only-do-not-override-b92jn9).ant-modal .ant-modal-footer .ant-btn+.ant-btn:not(.ant-dropdown-trigger)) {
    color: #fff !important;
}
</style>
